package com.xm.service.impl;

import com.xm.model.Msg;
import com.xm.service.RabbitService;
import com.xm.util.old.JacksonUtil;
import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service("rabbitService")
public class RabbitServiceImpl implements RabbitService {
    @Autowired
    private RabbitTemplate rabbitTemplate;

    @Override
    public void sendMsg(String exchange, String routingKey, Object message) {
        rabbitTemplate.convertAndSend(exchange, routingKey, message);
    }

    @Override
    public void sendDirectMsg(Object message) {
        rabbitTemplate.setExchange("directExchange");
        rabbitTemplate.setRoutingKey("directRoutingKey");
        rabbitTemplate.convertAndSend(message);
    }

    @Override
    public void sendAckMsg(String routingKey, Object message) {
        rabbitTemplate.convertAndSend(routingKey, message);
    }

    @Override
    public void sendAckCallbackMsg(String routingKey, Object message) {
        //为消息添加唯一ID，测试消费消息后的onSuccess与onFailure函数
        Msg msg = JacksonUtil.string2Obj(message.toString(), Msg.class);
        assert msg != null;
        CorrelationData correlationData = new CorrelationData(msg.getMsgId());
        String msgStr = JacksonUtil.obj2String(msg);
        rabbitTemplate.convertAndSend(routingKey, message, correlationData);
    }
}
